package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.Classify;
import com.chen.pfm.entity.DisplayBill;
import com.chen.pfm.entity.ResultVo;
import com.chen.pfm.provider.ClassifyProvider;
import com.chen.pfm.utils.*;

import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;

import ohos.agp.window.dialog.CommonDialog;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import java.io.IOException;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

public class ClassifiyManagementAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022001, "ClassifiyAbilitySlice");
    List<Classify> classifies_expenditure;
    List<Classify> classifies_income;
    List<Classify> classifies_property;
    ListContainer listContainer;
    ClassifyProvider classifyProvider;
    RadioContainer radioContainer;//单选按钮应该被重新刷新显示
    RadioButton classify_income;
    RadioButton classify_expenditure;
    RadioButton classify_property;
    int select;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_classifiy);

        try {
            classifies_expenditure = ClassifyDBUtil.queryAllClassifyByCtype1(this, 1);
            classifies_income = ClassifyDBUtil.queryAllClassifyByCtype1(this, 2);
            classifies_property = ClassifyDBUtil.queryAllClassifyByCtype1(this, 3);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }

        //返回按钮监听
        findComponentById(ResourceTable.Id_goback_btn).setClickedListener(component -> terminate());

        //分类列表的容器
        listContainer = (ListContainer) findComponentById(ResourceTable.Id_ListContainer_items_classify);


        FlushUIData(classifies_expenditure);
        //单选按钮容器
        radioContainer = (RadioContainer) findComponentById(ResourceTable.Id_RadioContainer);
        radioContainer.setMarkChangedListener((radioContainer, i) -> {
            select = i;
        });
        //按键收入监听
        classify_income = (RadioButton) findComponentById(ResourceTable.Id_classify_income);
        classify_income.setClickedListener((component) -> FlushUIData(classifies_income));
        //按键支出监听
        classify_expenditure = (RadioButton) findComponentById(ResourceTable.Id_classify_expenditure);
        classify_expenditure.setClickedListener((component) -> FlushUIData(classifies_expenditure));
        //按键支出监听
        classify_property = (RadioButton) findComponentById(ResourceTable.Id_classify_property);
        classify_property.setClickedListener((component) -> FlushUIData(classifies_property));


        //添加一个分类标签按键监听
        findComponentById(ResourceTable.Id_add_a_classify).setClickedListener((component) -> {
            presentForResult(new AddOneClassifySlice(), new Intent(), 1005);

        });

        //长按监听--->删除操作
        listContainer.setItemLongClickedListener((container, component, i, id) -> {
            Classify classify = (Classify) listContainer.getItemProvider().getItem(i);
            deleteClassify(classify);
            return false;
        });

    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        MyToast.showMyToast(this, "返回1005事件处理");
        if (requestCode == 1005) {
            if (resultIntent == null) {
                return;
            }
            try {
                classifies_expenditure = ClassifyDBUtil.queryAllClassifyByCtype1(this, 1);
                classifies_income = ClassifyDBUtil.queryAllClassifyByCtype1(this, 2);
                classifies_property = ClassifyDBUtil.queryAllClassifyByCtype1(this, 3);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            }
            if (select == 4) {
                FlushUIData(classifies_property);
            } else if (select == 2) {
                FlushUIData(classifies_income);
            } else {
                //select==0默认值
                FlushUIData(classifies_expenditure);
            }

            listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                    // 建议在onComponentBoundToWindow监听或者其他事件监听中调用。
                    classifyProvider.notifyDataChanged();
                    // displayBillProvider.notifyDataChanged();
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {
                }
            });
            return;
        }
    }

    void deleteClassify(Classify delclassify) {
        if (delclassify == null) {
            MyToast.showMyToast(this, "列表项逆转对象错误！");
            HiLog.error(LABEL, "列表项逆转对象错误！");
            return;
        }

        //布局加载
        Component parse = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_dialog_delete_confirm, null, false);
        //创建显示气窗
        CommonDialog dialog = new CommonDialog(this);
        dialog.setOffset(0, 10);
        dialog.setContentCustomComponent(parse);
        dialog.setSize(MATCH_CONTENT, MATCH_CONTENT);
        //取消按钮
        Button logout_cancel = (Button) parse.findComponentById(ResourceTable.Id_logout_cancel);
        //确定按钮
        Button logout_ok = (Button) parse.findComponentById(ResourceTable.Id_logout_ok);
        //预算设置的输入框
        Text classify_name_text = (Text) parse.findComponentById(ResourceTable.Id_classify_name_text);
        if (delclassify.getCname() == null) {
            MyToast.showMyToast(this, "分类标签属性错误！");
            HiLog.error(LABEL, "分类标签属性错误！");
            return;
        }
        //改变渲染的数据，显示要删除的标签
        classify_name_text.setText(delclassify.getCname());

        getUITaskDispatcher().asyncDispatch(() -> {
            dialog.show();
            logout_cancel.setClickedListener(c -> {
                dialog.destroy();
                MyToast.showMyToast(this, "已取消");
            });
            logout_ok.setClickedListener(c -> {
                //进行判断
                boolean isExist = false;
                if (delclassify.getCtype_2() == 0) {
                    MyToast.showMyToast(this, "系统分类不可删除！");
                    HiLog.error(LABEL, "用户操作删除系统分类，已拒绝！");
                    dialog.hide();
                    return;
                } else {//如果是用户自定义的分类，存在账单也不可以删掉
                    //查询是否存在该分类的账单
                    try {
                        isExist = AccountDBUtil.queryIsExistsAccountByCid(this, delclassify.getCid());
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }
                    if (isExist == true) {
                        MyToast.showMyToast(this, "该分类存在账单不可删除！");
                        dialog.hide();
                        return;
                    } else {
                        dialog.hide();
                        //ui刷新线程显示
                        try {
                            int del = ClassifyDBUtil.deleteClassifyByCid(this, delclassify.getCid());
                            if (del > 0) {
                                MyToast.showMyToast(this, "本地分类标签删除成功！");
                                delRemoteDate(MyUtil.deleteClassifyByCid, delclassify.getCid());
                            }
                        } catch (DataAbilityRemoteException e) {
                            e.printStackTrace();
                        }


                    }
                }
            });//点击事件

        });//ui线程
    }

    private void delRemoteDate(String url, String cid) {
        //开一个线程更新用户信息
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            ResultVo resultVo;
            Gson gson = new Gson();
            //转化为json
            String getRequestjson = null;
            RequestBody requestBody = new FormBody.Builder()
                    .add("cid", cid)
                    .build();
            //转化为json
            try {
                getRequestjson = HttpRequestUtil.sendPostRequestByOkHttp(url, requestBody);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (getRequestjson == null || getRequestjson.contains("not found")) {
                HiLog.info(LABEL, "无法连接到网络！");
                getUITaskDispatcher().asyncDispatch(() -> {
                    MyToast.showMyToast(this, "无法连接到网络");
                });
                return;
            } else {
                try {
                    resultVo = gson.fromJson(getRequestjson, ResultVo.class);
                } catch (Exception e) {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "gson解析返回对象失败，请确定服务器是否开启");
                    });
                    HiLog.error(LABEL, "有网络但是连接不到服务器时返回数据为：" + getRequestjson);
                    return;
                }

                if (resultVo == null) {//返回对象进行解析
                    HiLog.info(LABEL, "返回对象为空！");
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "返回为空,数据丢失！");
                    });
                    return;
                } else {
                    getUITaskDispatcher().asyncDispatch(() -> {
                        MyToast.showMyToast(this, "状态码" + resultVo.getCode() + " " + resultVo.getMsg());
                        if (resultVo.getCode() == 200) {
                            terminate();
                        }
                    });
                }
            }


        });//全局线程
    }

    //按键支出监听
    private void FlushUIData(List<Classify> list) {
        //此处要考虑需不需要加入ui线程
        getUITaskDispatcher().asyncDispatch(() -> {
            //2022.4.26这种写法性能优化有问题
         //   listContainer.setItemProvider(new ClassifyProvider(list, this));

            classifyProvider = new ClassifyProvider(list, this);
            listContainer.setItemProvider(classifyProvider);
            //点击进入详情页面
            listContainer.setItemClickedListener((container, component, i, id) -> {

            });

        });
    }


}
